package com.functest.orm.legacy

import com.functest.util.OrmUtil

class SimpleMapper {
    private static initMixIns = OrmUtil.instance  //We use Map.swapKeysWithValues and Map.applyMapping methods declared in Util
    private Map dbMapping;
    private Closure<Map> enrichClosure = null;
    @Lazy String allFields = {
        List list = []
        dbMapping.values().each{
          list<<"\"${it}\""
        }
        list.join(",")

    }()

    public Map getDbMapping(){
        dbMapping
    }




    private void setDbMapping(){throw new UnsupportedOperationException()}
    private void setAllFields(){throw new UnsupportedOperationException()}

    public Map mapRowForConstructor(Map row, Closure<Map> enrichClosure = this.enrichClosure){
        Map bean = mapRow(row, enrichClosure)

        def toRemove=[]
        bean.each { Map.Entry entry ->
            if (!entry.getValue()) toRemove.add(entry.getKey())
        }
        toRemove.each { String entry ->
            bean.remove(entry)
        }

        bean
    }

    public Map mapRow(Map row, Closure<Map> enrichClosure = this.enrichClosure){
        Map bean = new HashMap((Map) row.applyMapping(dbMapping.swapKeysWithValues()))
        if (enrichClosure!=null){
            bean = bean.enrich(enrichClosure);
        }
        bean
    }

}
